package com.github.chirspan.xaas.auth.listener;

import com.github.chirspan.xaas.security.service.AuthUserDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Map;

/**
 * @className: AuthenticationSuccessEventListener
 * @description: <p></p>
 * @author: chenpan
 * @date: 2021/6/18 10:29
 **/
@Component
@Slf4j
public class AuthenticationSuccessEventListener implements ApplicationListener<AuthenticationSuccessEvent> {

    @Override
    public void onApplicationEvent(AuthenticationSuccessEvent event) {
        //这里的事件源除了登录事件（UsernamePasswordAuthenticationToken）还有可能是token验证事件源（OAuth2Authentication）
        if (!event.getSource().getClass().getName().equals("org.springframework.security.authentication.UsernamePasswordAuthenticationToken")) {
            return;
        }
        // 排除client的认证
        if (event.getAuthentication().getPrincipal() instanceof AuthUserDetail) {
            log.debug("登录成功");
            RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
            Map<String, String[]> authParameters = ((ServletRequestAttributes) requestAttributes).getRequest().getParameterMap();
            // todo 记录登录日志
        }
    }
}
